package com.roomio.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.roomio.core.security.model.User;
import com.roomio.core.security.service.UserInfoService;

@RequestMapping("/userinfoes")
@Controller
public class UserInfoController {
	
	@Autowired
	private UserInfoService userInfoService;
	
    @RequestMapping(method = RequestMethod.POST)
    public String create(@Valid User user, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, user);
            return "userinfoes/create";
        }
        uiModel.asMap().clear();
        userInfoService.persist(user);
        return "redirect:/userinfoes/" + encodeUrlPathSegment(user.getIdentityUrl().toString(), httpServletRequest);
    }
    
    	@RequestMapping(params = "form", produces = "text/html")
    	public String createForm(Model uiModel) {
        populateEditForm(uiModel, new User());
        return "userinfoes/create";
    }
    
    @RequestMapping(value = "/{id_}", produces = "text/html")
    public String show(@PathVariable("id_") Long id_, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("userinfo", userInfoService.findById(id_));
        uiModel.addAttribute("itemId", id_);
        return "userinfoes/show";
    }
    
    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("userinfoes", userInfoService.findUserInfoEntries(firstResult, sizeNo));
            float nrOfPages = (float) userInfoService.countUserInfoes() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("userinfoes", userInfoService.findAllUserInfoes());
        }
        addDateTimeFormatPatterns(uiModel);
        return "userinfoes/list";
    }
    
    @RequestMapping(value="/users",params = "term")
    public @ResponseBody List<String> allUser( Model uiModel) {
    	List<String> userList = new ArrayList<String>();
    	List<User>  list =userInfoService.findAllUserInfoes();
    	for (User user : list) {
    		userList.add(user.getEmail());
		}
    	return userList;
    }
    
    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid User user, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, user);
            return "userinfoes/update";
        }
        uiModel.asMap().clear();
        userInfoService.merge(user);
        return "redirect:/userinfoes/" + encodeUrlPathSegment(user.getIdentityUrl().toString(), httpServletRequest);
    }
    
    @RequestMapping(value = "/{id_}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id_") Long id_, Model uiModel) {
        populateEditForm(uiModel, userInfoService.findById(id_));
        return "userinfoes/update";
    }
    
    @RequestMapping(value = "/{id_}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id_") Long id_, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
    	userInfoService.delete(id_);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/userinfoes";
    }
    
    void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("userInfo_createddate_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }
    
    void populateEditForm(Model uiModel, User user) {
        uiModel.addAttribute("userInfo", user);
        addDateTimeFormatPatterns(uiModel);
    }
    
    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
